package HttpServlet;

import Entity.DataDTO3;
import Entity.Userinformation;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

@WebServlet(urlPatterns = {"/upload3"})
@MultipartConfig(location = "C:\\Users\\78733\\Desktop\\Experiment3\\src\\main\\webapp\\image")// location改为本地的绝对路径
public class informationservlet extends HttpServlet {

    EntityManager em = Persistence.createEntityManagerFactory("MyJPADemoPU").createEntityManager();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        Map<String,String> userName = (Map<String, String>) request.getSession().getAttribute("userName");

        // 获取请求项，封装成Part对象
        // request.getPart方法的传参为前端页面from表单的input文件组件的name值
        Part part = request.getPart("file");

        // part.getSubmittedFileName()方法获取上传文件的文件名
        String fileName = part.getSubmittedFileName();
        // 根据@MultipartConfig的location配置的目录上传文件，直接传参文件名即可。
        part.write(fileName);

        EntityTransaction tx = em.getTransaction();
        Userinformation userinformation=em.find(Userinformation.class,userName.get("用户名"));
        try {
            tx.begin();
            userinformation.setImg(fileName);
            tx.commit();
        }catch (Exception ex) {
            throw  new ServletException();
        } finally {
            //close the em to release any resources held up by the persistebce provider
            em.close();
        }

        userName.put("头像",fileName);

        response.getWriter().write("头像上传成功！");

    }

}
